<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Wx extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		$this->load->database('default');
	}

	public function index()
	{
		echo isset($_GET["echostr"])?$_GET["echostr"]:'';
		
		$postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"])?$GLOBALS["HTTP_RAW_POST_DATA"]:'';
		log_message('error', print_r($postStr,true));
		
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			 $this->fromUsername = $postObj->FromUserName;
             $this->toUsername = $postObj->ToUserName;
             
             $this->db->insert('message',array(
             	'FromUserName'=>$postObj->FromUserName,
             	'Format'=>isset($postObj->Format)?$postObj->Format:'',
             	'MsgType'=>$postObj->MsgType,
             	'MediaId'=>isset($postObj->MediaId)?$postObj->MediaId:'',
             	'Recognition'=>isset($postObj->Recognition)?$postObj->Recognition:'',
             	'Content'=>isset($postObj->Content)?$postObj->Content:'',
             	'PicUrl'=>isset($postObj->PicUrl)?$postObj->PicUrl:'',
             	'ThumbMediaId'=>isset($postObj->ThumbMediaId)?$postObj->ThumbMediaId:'',
             	'Event'=>isset($postObj->Event)?$postObj->Event:'',
             ));
             
             if($postObj->MsgType == 'voice')
             {
             	$r = $this->autoMsg($postObj->Recognition);
             	$r = json_decode($r,true);
             	$this->responseText($r['result']['content']);
             	
             }elseif($postObj->MsgType == 'text')
             {
             	$r = $this->autoMsg($postObj->Content);
             	$r = json_decode($r,true);
             	$this->responseText($r['result']['content']);
             }
             else {
             	$this->responseText('hello');
             }
		}
		
	}
	public function responseText($content,$type='text'){
		 $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
					</xml>";
		$resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, time(), $type, $content);
		echo $resultStr;
		exit;
	}
	public function fileauth()
	{
		echo '201711111533452nx4fmehsa33lls7tk98oq0rewj2prmkjspkr87jcoo5ykvyp6';
	}
	
	public function test()
	{
		$this->load->library('weixin');
		$token = $this->weixin->get_token();
		$u = array();
		foreach($this->db->query("select id,MsgType,MediaId,PicUrl,ThumbMediaId from message where IsOk=0 and MsgType in('video','image')")->result_array() as $v)
		{
			if($v['MsgType']=='image')
			{
				$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token={$token}&media_id={$v['MediaId']}";
				$res = curl($url);
				if(write_file('./application/cache/'.$v['MediaId'].'.jpg',$res))
				{
					$u[] = array('IsOk'=>1,'id'=>$v['id']);
				}
				$this->qupload('./application/cache/'.$v['MediaId'].'.jpg');
			}
			if($v['MsgType']=='video')
			{
				$url = "http://api.weixin.qq.com/cgi-bin/media/get?access_token={$token}&media_id={$v['MediaId']}";
				$res = curl($url);
				write_file('./application/cache/'.$v['MediaId'].'.mp4',$res);
				$this->qupload('./application/cache/'.$v['MediaId'].'.mp4');
				$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token={$token}&media_id={$v['ThumbMediaId']}";
				$res = curl($url);
				write_file('./application/cache/'.$v['ThumbMediaId'].'.jpg',$res);
				$this->qupload('./application/cache/'.$v['ThumbMediaId'].'.jpg');
				$u[] = array('IsOk'=>1,'id'=>$v['id']);
			}
		}
		if(count($u)>0)
		{
			$this->db->update_batch('message',$u,'id');
		}
	}
	
	public function qupload($file = '')
	{
		$fname = basename($file); // 获取文件名
//		$ext = substr(strrchr($file, '.'), 1);  // 获取扩展名
		$ch =curl_init();
		$cfile = curl_file_create($file);
		$this->load->library('qiniu');
		$token = $this->qiniu->token();
		$post = array('file'=>$cfile,'token'=>$token,'key'=>basename($file));
		$header[] = "Content-Type:multipart/form-data";
		curl_setopt($ch,CURLOPT_URL,'https://upload-z1.qbox.me');
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
		curl_setopt($ch, CURLOPT_INFILESIZE,filesize($file));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$res = curl_exec($ch);
		curl_close($ch);
		$res = json_decode($res,true);
//		copy($file,'/tmp/upload/'.$fname); //拷贝到新目录
//  		unlink($file); //删除旧目录下的文件
		echo $res['key']."\n";
	}
	
	
	public function autoMsg($querys = '')
	{
		$host = "http://jisuznwd.market.alicloudapi.com";
	    $path = "/iqa/query";
	    $method = "GET";
	    $appcode = "b0211244eeec4f46952bfdcba3c15f54";
	    $headers = array();
	    array_push($headers, "Authorization:APPCODE " . $appcode);
	    $querys = "question=".$querys;
	    $bodys = "";
	    $url = $host . $path . "?" . $querys;
	
	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	    curl_setopt($curl, CURLOPT_FAILONERROR, false);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($curl, CURLOPT_HEADER, true);
	    if (1 == strpos("$".$host, "https://"))
	    {
	        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	    }
	    $msg = curl_exec($curl);
	    $msg = explode("\n", $msg);
	    return $msg[count($msg)-1];
	}
}
